<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleList" border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id" :class="['bdbottom', i1 === 0 ? 'bdtop' : '','vcenter']">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRoleById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2 === 0 ? '' : 'bdtop','vcenter']">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRoleById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRoleById(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 编辑角色 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialog(scope.row.id)">编辑</el-button>
            <!-- 删除角色 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleRole(scope.row.id)">删除</el-button>
            <!-- 分配权限 -->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="roleDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="权限列表"
      :visible.sync="roleDialogVisible"
      width="40%" @close="roleDialogClose">
      <el-tree :data="rightsList" :props="treeProps" show-checkbox default-expand-all node-key="id" :default-checked-keys="defKeys" ref="treeRef">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRightsForRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="40%">
      <el-form ref="addRoleRef" :v-model="addRoleForm" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色的对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="40%">
      <el-form ref="editRoleRef" :v-model="editRoleForm" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      roleList: [],
      // 分配权限对话框
      roleDialogVisible: false,
      // 添加角色对话框
      addDialogVisible: false,
      // 修改角色对话框
      editDialogVisible: false,
      // 添加角色数据
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色数据
      editRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 权限列表
      rightsList: [],
      // 权限列表显示的字段
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      // 即将分配权限的角色Id
      roleId: ''
    }
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleList = res.data
    },
    // 添加角色
    async addRole() {
      const { data: res } = await this.$http.post('roles', { roleName: this.addRoleForm.roleName, roleDesc: this.addRoleForm.roleDesc })
      if (res.meta.status !== 201) return this.$message.error('创建角色失败')
      this.$message.success('创建角色成功')
      this.addRoleForm.roleDesc = ''
      this.addRoleForm.roleName = ''
      this.getRoleList()
      this.addDialogVisible = false
    },
    // 编辑修改角色的对话框
    async editDialog(roleId) {
      const { data: res } = await this.$http.get(`roles/${roleId}`)
      if (res.meta.status !== 200) return this.$message.error('网络正忙，请稍后再试')
      this.editRoleForm.roleName = res.data.roleName
      this.editRoleForm.roleDesc = res.data.roleDesc
      this.roleId = roleId
      this.editDialogVisible = true
    },
    // 修改角色
    async editRole() {
      const { data: res } = await this.$http.put(`roles/${this.roleId}`, { roleName: this.editRoleForm.roleName, roleDesc: this.editRoleForm.roleDesc })
      if (res.meta.status !== 200) return this.$message.error('修改角色信息失败')
      this.$message.success('修改角色信息成功')
      this.getRoleList()
      this.editDialogVisible = false
    },
    // 删除角色
    deleRole(roleId) {
      this.$confirm('确认删除该角色，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${roleId}`)
        if (res.meta.status !== 200) return this.$message.error('删除角色失败')
        this.$message.success('删除角色成功')
        this.getRoleList()
      }).catch(() => {
        this.$message.info('已取消删除')
      });
    },
    // 移除角色权限
    removeRoleById(role, rightId) {
      this.$confirm('是否取消该权限', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status !== 200) return this.$message.error('删除权限失败')
        this.$message.success('删除权限成功')
        role.children = res.data
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 分配权限按钮的操作
    async roleDialog(role) {
      const { data: res } = await this.$http.get('rights/tree')
      this.rightsList = res.data
      this.roleId = role.id
      // 通过递归查询角色已有的权限
      this.getDefKeys(role, this.defKeys)
      this.roleDialogVisible = true
    },
    // 分配权限对话框关闭后重置defKeys数组
    roleDialogClose() {
      this.defKeys = []
    },
    // 得到角色默认已有的权限Id
    getDefKeys(node, arr) {
      // 检测当前节点是否是三级节点，如果是添加Id
      if (!node.children) {
        return arr.push(node.id)
      }
      // 如果不是三级节点，递归调用查询三级节点的Id
      node.children.forEach(item => this.getDefKeys(item, arr))
    },
    // 为角色分配权限
    async addRightsForRole() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const strId = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: strId })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.getRoleList()
      this.roleDialogVisible = false
    }
  },
  created() {
    this.getRoleList()
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
